package com.xunk.equipment.service.zhijia.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.xunk.common.core.domain.EquipmentResponse;
import com.xunk.common.core.utils.StringUtils;
import com.xunk.common.redis.service.RedisService;
import com.xunk.equipment.domain.EquipmentDO;
import com.xunk.equipment.mapper.EquipmentMapper;
import com.xunk.equipment.service.BaseService;
import com.xunk.equipment.service.IOneKeySwitchService;
import com.xunk.equipment.vo.response.OneKeySwitchInfoResponse;
import com.xunk.equipment.vo.response.SwitchKey;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @ProjectName: HIM
 * @Package: com.xunk.equipment.service.zhijia.service
 * @ClassName: UhomeOneKeySwitchService
 * @Author: luanzhiwei
 * @Description: 智家一键开关实现类
 * @Date: 2021/6/15 13:25
 * @Version: 1.0
 */
@Service(value = "uplus-one-key-switch")
@Slf4j
public class UhomeOneKeySwitchService implements IOneKeySwitchService {

    @Autowired
    private ZhijiaService zhijiaService;
    @Autowired
    private EquipmentMapper equipmentMapper;
    @Autowired
    private BaseService baseService;
    @Autowired
    private RedisService redisService;

    /**
     * 获取设备当前状态值信息
     *
     * @param equipmentDO 当前设备信息，包含设备id，设备厂商
     * @return
     */
    @Override
    public EquipmentResponse getEquipmentInfo(EquipmentDO equipmentDO) {
        /*
        redis缓存的数据格式
        {
            "reported": {
            "nickName": "客厅主灯",
                    "floorName": "-3",
                    "roomName": "房间1",
                    "onOffStatus": "true"
        },
            "shadowInfo": {
            "online": true,
                    "onoffTimestamp": "1623718948365",
                    "reportedTimestamp": "1623735211897"
        }*/

        String deviceSn = equipmentDO.getDeviceSn();
        final Long homeId = equipmentMapper.selectHomeIdByDeviceSn(deviceSn);
        Map<String, Object> cacheMap = zhijiaService.getShadowByDeviceSn(homeId, equipmentDO.getDeptId(), deviceSn);
        OneKeySwitchInfoResponse response = new OneKeySwitchInfoResponse();
        response.setDeviceName(equipmentDO.getDeviceName());
        response.setDeviceSn(deviceSn);
        response.setDeviceType(equipmentDO.getDeviceType());
        //reported 包含全部设备属性
        final Map reported = (Map) cacheMap.get("reported");
        final Boolean onOffStatus = Convert.toBool(reported.get("onOffStatus"));
        response.setLeft(new SwitchKey(onOffStatus));
        final List<Map<String, Object>> module = (List<Map<String, Object>>) cacheMap.get("module");
        final Map moduleInfo = module.get(0);
        final Map info = (Map) moduleInfo.get("moduleInfos");
        final Optional<Map<String, Object>> first = module.stream().filter(item -> ObjectUtil.equals(item.get("moduleType"), "basemodule")).findFirst();
        if (first.isPresent()) {
            final Map<String, Object> firstMap = first.get();
            final Map firstInfo = (Map) firstMap.get("moduleInfos");
            response.setModel(Convert.toStr(firstInfo.get("hardwareType")));
        }
        response.setFirmWare(Convert.toStr(info.get("softwareVers")));
        response.setSerialNumber(Convert.toStr(cacheMap.get("wifiType")));
        response.setSupplier(equipmentDO.getSupplier());
        response.setMac(Convert.toStr(cacheMap.get("deviceId")));
        response.setCandidateModel(baseService.getCandidateModel(equipmentDO.getDeviceBaseId()));


        final Map shadowInfo = (Map) cacheMap.get("shadowInfo");
        response.setOnline(Convert.toBool(shadowInfo.get("online"), false));
        equipmentMapper.updateEquipmentOnline(equipmentDO.getDeviceSn(), response.getOnline() ? 1L : 0L);


        return response;
    }

    /**
     * 控制设备
     *
     * @param equipmentDO 当前设备信息，包含设备id，设备厂商
     * @param type        控制类型，如温度、开关、模式
     * @param value       操作目标值  如 20°(20)、open(true)、冷风模式(3)
     * @return
     */
    @Override
    public Boolean control(EquipmentDO equipmentDO, String type, String value) {
        boolean flag = false;
        if (StringUtils.equals(type, "on")) {
            flag = zhijiaService.control(equipmentDO, "onOffStatus", value);
        }
        if (flag) {
            try {
                final String deviceSn = equipmentDO.getDeviceSn();
                final Long homeId = equipmentMapper.selectHomeIdByDeviceSn(deviceSn);
                final Long deptId = equipmentDO.getDeptId();
                Map<String, Object> cacheMap = zhijiaService.getShadowByDeviceSn(homeId, deptId, deviceSn);
                final Map reported = (Map) cacheMap.get("reported");
                reported.put("onOffStatus", Convert.toBool(value));
                cacheMap.put("reported", reported);
                String ancestor = baseService.findAncestorByDeptId(deptId);
                String key = ancestor.concat(":").concat(deviceSn);
                redisService.setCacheMap(key, cacheMap);
            } catch (Exception exception) {
                log.error("控制设备成功，刷新设备影子异常：{}", exception);
            }
        }
        return flag;
    }

}
